<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/11/7
 * Time: 17:32
 */

namespace app\api\controller;


use addons\ask\model\Comment;
use app\admin\model\user\UserExpertsPrice;
use app\common\controller\Api;
use app\common\model\MoneyLog;

class Order extends Api
{

    protected $noNeedLogin = [];
    protected $noNeedRight = '*';
    public function index(){
        echo 1;die;
    }
    /**
     * 订单创建
     * */
    public function create_order()
    {
        $params = $this->request->param();
        $isPay = [
            'type' => $params['type'],
            'experts_id' => $params['experts_id']
        ];
        $order = new \app\admin\model\order\Order();

        if ($order->isPayExist($isPay)) {
            $this->error('当前存在未付款订单', '',20);
        }
        $uep = new UserExpertsPrice();
        if ($params['type'] == 1) {
            $price = $uep->where(['uid' => $params['experts_id']])->field('sound_price')->find();
            $price = $price['sound_price'];
        } elseif ($params['type'] == 2) {
            $price = $uep->where(['uid' => $params['experts_id']])->field('video_price')->find();
            $price = $price['video_price'];
        } else {
            $this->error('类型错误，请重新选择');
        }
        $insertData = [
            'uid' => $this->auth->id,
            'createtime' => date('Y-m-d H:i:s', time()),
            'type' => $params['type'],
            'status' => '0',
            'pay_status' => '0',
            'experts_id' => $params['experts_id'],
            'order_sn' => date('YmdHis') . sprintf("%06d", $this->auth->id) . mt_rand(10000, 99999),
            'price' => $price,
            'consult_type' => $params['consult_type']
        ];
        $order = new \app\admin\model\order\Order();
        $order->save($insertData);
        $id = $order->getLastInsID();
        $this->success('订单创建成功', ['order_id' => $id]);
    }


    /**
     * 用户端订单管理
     * */
    public function user_order()
    {
        $status = $this->request->param('status'); //1 未付款 2 已付款待咨询  3 已完成 0 所有
        $page = $this->request->param('page', '1'); //暂不启用显示数量
        $start_limit = ($page * 10) - 10;
        $order = new \app\admin\model\order\Order(); 
        switch ($status) {
            case 0:         // 全部订单
                $where = [
                    'o.status' => ['in', [0, 1, 2, 3, 4]],
                    'o.uid' => $this->auth->id
                ];
                break;
            case 1:         // 未付款
                $where = [
                    'o.status' => 0,
                    'o.pay_status' => 0,
                    'o.uid' => $this->auth->id
                ];
                break;
            case 2:         // 待确认 待服务  待评价
                $where = [
                    'o.status' => ['in', [1, 2, 3]],
                    'o.pay_status' => 1,
                    'o.uid' => $this->auth->id
                ];
                break;
            case 3:         //已完成
                $where = [
                    'o.status' => 4,
                    'o.pay_status' => 1,
                    'o.uid' => $this->auth->id
                ];
                break;
            default:
                $this->error('error');
        }
        $list = $order
            ->alias('o')
            ->join('fa_user u', 'o.experts_id = u.id')
            ->order('order_id', 'desc')
            ->field('u.nickname,u.avatar,o.order_id,o.createtime,o.type,o.status,o.appoint_time,o.price,o.consult_type,o.is_comment')
            ->where($where)
            ->limit($start_limit,10)
            ->select();
        if ($list) {
            $list = collection($list)->toArray();
            foreach ($list as $key => $value) {
                if ($value['type'] == 1) {
                    $list[$key]['type'] = '音频通话';
                } else {
                    $list[$key]['type'] = '视频通话';
                }
                $list[$key]['status'] = $this->getStatus($value['status']);
            }
        } else {
            $list = [];
        }
        $this->success('成功', $list, 200);
    }

    /**
     * 获取状态
     * @param $status 状态
     * */
    public function getStatus($status)
    {
        $s = '';
        switch ($status) {
            case 0:
                $s = '待支付';
                break;
            case 1:
                $s = '待确认';
                break;
            case 2:
                $s = '待服务';
                break;
            case 3:
                $s = '待评价';
                break;
            case 4:
                $s = '订单完成';
                break;

            default:
                $s = '状态错误';
        }

        return $s;

    }

    /**
     * 用户订单详情
     **/
    public function user_detail()
    {
        $order_id = $this->request->param('order_id');
        $order = new \app\admin\model\order\Order();
        $where = [
            'order_id' => $order_id,
            'uid' => $this->auth->id
        ];
        $orderInfo = $order->where($where)->alias('o')
            ->join('fa_user u', 'o.experts_id = u.id')
            ->order('order_id', 'desc')
            ->field('u.nickname,u.avatar,o.order_id,o.createtime,o.type,o.status,o.appoint_time,o.price,o.consult_type,o.pay_type,o.pay_type,o.pay_time,o.order_sn')
            ->find();
        if ($orderInfo) {
            if ($orderInfo['type'] == 1) {
                $orderInfo['type'] = '音频通话';
            } else {
                $orderInfo['type'] = '视频通话';
            }
            $orderInfo['status'] = $this->getStatus($orderInfo['status']);
            $this->success('成功', $orderInfo, 200);
        } else {
            $this->success('成功', $orderInfo, 200);
        }
    }

    /**
     * 用户确定完成订单
     * */
    public function confirm_order()
    {
        $order_id = $this->request->param('order_id');
        $order = new \app\admin\model\order\Order();
        $orderInfo = $order
            ->where(['uid' => $this->auth->id, 'order_id' => $order_id, 'pay_status' => '1'])
            ->find();
        if (!$orderInfo) {
            $this->error('订单信息错误');
        }
        $commission_config = (config('commission_config')) / 100;
        $money = $orderInfo['price'] * $commission_config;
        \app\common\model\User::get($orderInfo['experts_id'])->setInc('money', $money);
        $moneyLog = new MoneyLog();
        $moneyLogInfo = $moneyLog->where('user_id', $orderInfo['experts_id'])->find();
        $moneyInsert = [
            'user_id' => $orderInfo['experts_id'],
            'money' => $money,
            'before' => $moneyLogInfo->after,
            'after' => $moneyLogInfo->after + $money,
            'memo' => '订单服务完成，佣金增加',
            'createtime' => date('Y-m-d H:i:s', time()),
            'type' => '1',
            'order_id' => $order_id
        ];
        $moneyLog->insert($moneyInsert);
        $order->where('order_id', $order_id)->update(['status' => '4']);
        $this->success('成功', '', 200);
    }

    /**
     * 订单评价
     * */

    public function order_add_comment(){
        $params = $this->request->param();
        if(!isset($params['comment']) || empty($params['comment'])){
            $this->error('请输入评价内容');
        }
        $comment = trim($params['comment']);
        $order_id = $params['order_id'];

        $order = new \app\admin\model\order\Order();
        $orderInfo = $order->get($order_id);

        if($orderInfo->getAttr('is_comment')){
            $this->error('当前订单已评论');
        }

        $commentModel = new Comment();
        $data = [
            'user_id'       => $this->auth->id,
            'type'          => 'order',
            'source_id'     => $order_id,
            'reply_user_id' => 0,
            'content'       => $comment,
            'status'        => 'hidden',
            'experts_id'    =>$orderInfo->experts_id,
            'createtime'=>time()
        ];
        $insertId = $commentModel->insert($data);

        if($insertId){
            $order->where('order_id',$order_id)->update(['is_comment'=>'1']);
            $this->success('评论成功','',200);
        }else{
            $this->error('评论失败，请重试');
        }
    }
}